#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include <functional>
#include "InetAddr.hpp"

using namespace LogModule;

using func_t = std::function<std::string(const std::string&, InetAddr&)>;

const int defaultfd = -1;

//进行网络通信
class UdpServer
{
public:
    UdpServer(uint16_t port, func_t func)
    : _sockfd(defaultfd),
    //   _ip(ip),
      _port(port),
      _isrunning(false),
      _func(func)
    {

    }
   
    void Init()
    {
        //1.创建套接字Socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error!";
            exit(1);
        }
        LOG(LogLevel::INFO) << "socket success, socketfd: " << _sockfd;
        //2.绑定socket信息，ip和端口
        //2.1 填充sockaddr_in结构体
        struct sockaddr_in local;
        bzero(&local, sizeof(local));

        local.sin_family = AF_INET;
        //IP信息和端口信息，一定要发送到网络
        //本地格式->网络序列
        local.sin_port = htons(_port);
        //IP也是 1.IP转成4字节 2.4字节转成网络序列
        //in_addr_t inet_addr(const char *cp);
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());

        //全0 ip
        //可以接收端口号一样的所有IP信息
        local.sin_addr.s_addr = INADDR_ANY;

        //2.2 绑定
        //服务器端要显式的bind,IP和端口必须是众所周知且不能轻易改变的！
        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(2);
        }

        LOG(LogLevel::INFO) << "bind success, socket: " << _sockfd;

    }

    void Start()
    {
        _isrunning = true;
        //接收数据
        while(_isrunning)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);

            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);

            if(n > 0)
            {
                buffer[n] = 0;

                InetAddr client(peer);
                
                //1.信息内容 2.谁发的
                // LOG(LogLevel::INFO) << "[" << peer_ip << ":" << peer_port << "]# " << buffer;
                
                std::string result = _func(buffer, client);

                //2.发消息
                // std::string echo_string = "server echo@ ";
                // echo_string += buffer;
                // sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (struct sockaddr*)&peer, len);

                sendto(_sockfd, result.c_str(), result.size(), 0, (struct sockaddr*)&peer, len);
            }
        }

    }

    ~UdpServer()
    {

    }

private:
    int _sockfd;
    uint16_t _port;
    // std::string _ip; // 用的是字符串风格，点分十进制

    bool _isrunning;
    // 服务器的回调函数，用来进行对数据进行处理
    func_t _func;
};